﻿using System;
using System.Linq;
using System.Web;
using Microsoft.ApplicationServer.Http.Dispatcher;
using System.Net.Http;
using System.Net;
using System.Text;

namespace ServiceWeb.Libs {

    public class BasicHttpAuthorizationOperationHandler : HttpOperationHandler<HttpRequestMessage, HttpRequestMessage> {

        BasicHttpAuthorizationAttribute basicHttpAuthorizationAttribute;

        public BasicHttpAuthorizationOperationHandler(BasicHttpAuthorizationAttribute authorizeAttribute)
            : base("response") {
            basicHttpAuthorizationAttribute = authorizeAttribute;
        }

        protected override HttpRequestMessage OnHandle(HttpRequestMessage input) {
            if (Authenticate(input)) {
                return input;
            } else {
                var challengeMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                challengeMessage.Headers.Add("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", "www.siloam.com"));
                throw new HttpResponseException(challengeMessage);
            }
        }

        private bool Authenticate(HttpRequestMessage input) {
            if (!HttpContext.Current.Request.IsSecureConnection && !HttpContext.Current.Request.IsLocal) return false;
            
            if (!HttpContext.Current.Request.Headers.AllKeys.Contains("Authorization")) return false;
            
            string authHeader = HttpContext.Current.Request.Headers["Authorization"];

            if (TryGetPrincipal(authHeader)) {
                return true;
            }
            return false;
        }

        private bool TryGetPrincipal(string authHeader) {
            var creds = ParseAuthHeader(authHeader);
            if (creds != null) {
                if (TryGetPrincipal(creds[0], creds[1])) return true;
            }
            return false;
        }

        private string[] ParseAuthHeader(string authHeader) {
            if (authHeader == null || authHeader.Length == 0 || !authHeader.StartsWith("Basic")) return null;
            string base64Credentials = authHeader.Substring(6);
            string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(base64Credentials)).Split(new char[] { ':' });

            if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[0])) return null;
            return credentials;
        }

        private bool TryGetPrincipal(string userName, string password) {
            //basicHttpAuthorizationAttribute.UserRole;
            /// To do check if user in role
            if (userName.Equals("deny") && password.Equals("deny")) {
                return true;
            } else {
                return false;
            }
        }
    }
}